<template>
  <div class="outer-container">
    <!-- <div class="login-title">欢迎使用简易聊天机器人，在这里您可以畅所欲言</div> -->
    <div class="login-box">
      <div>
        <h2 class="login-form">请{{ useLoginForm ? "登录" : "注册" }}</h2>
        <el-form v-if="useLoginForm" ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
          <el-form-item prop="account">
            <el-input v-model="loginForm.account" clearable placeholder="账号" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" clearable show-password placeholder="密码" />
          </el-form-item>
          <el-button size="default" type="primary" :loading="loading" @click="onLogin(loginFormRef)">
            登录
          </el-button>
        </el-form>

        <el-form v-else ref="registerFormRef" :model="registerForm" :rules="registerRules as any" size="large">
          <el-form-item label="头像" required>
            <el-upload :headers="{ Authorization: `Bearer ${token}` }" :action="uploadApi" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-error="handleError">
              <img v-if="avatarShowUrl" :src="avatarShowUrl" class="avatar" />
            </el-upload>
          </el-form-item>
          <el-form-item prop="account" label="账号" required>
            <el-input v-model="registerForm.account" clearable placeholder="请输入账号" />
          </el-form-item>
          <el-form-item prop="nickname" label="昵称" required>
            <el-input v-model="registerForm.nickname" clearable placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="性别" required>
            <el-radio-group v-model="registerForm.sex">
              <el-radio label="1">男</el-radio>
              <el-radio label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="password" label="密码" required>
            <el-input v-model="registerForm.password" clearable show-password placeholder="请输入密码，至少8位" />
          </el-form-item>
          <el-form-item prop="confirmPassword" label="确认" required>
            <el-input v-model="registerForm.confirmPassword" clearable show-password placeholder="请确认密码" />
          </el-form-item>
          <el-button size="default" type="primary" :loading="loading" @click="onRegister(registerFormRef)">
            注册
          </el-button>
        </el-form>
        <div class="toggle-link" @click="toggleForm">
          <el-link :underline="false">
            {{ useLoginForm ? "没有账号？注册" : "已有账号？登录" }}
          </el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { register, login } from "../../api/user";

const router = useRouter();
const store = useStore();

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const token = localStorage.getItem("token") || "";
const uploadApi = baseUrl + "/api/upload/image";
const loading = ref(false);
const loginFormRef = ref<FormInstance>();
const registerFormRef = ref<FormInstance>();
const avatarShowUrl = ref("/default_head_img.png");

const useLoginForm = ref(true);

const loginForm = reactive({
  account: "",
  password: "",
});

const registerForm = reactive({
  avatar: "",
  account: "",
  nickname: "",
  sex: 0,
  password: "",
  confirmPassword: "",
});

const loginRules = reactive({
  account: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  console.log(rule);
  if (value !== registerForm.password) {
    callback(new Error("密码不一致!"));
  } else {
    callback();
  }
};

const registerRules = reactive({
  avatar: [{ required: true, message: "请上传头像", trigger: "blur" }],
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: "账号必须是英文字母或数字",
      trigger: "blur",
    },
  ],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 8,
      message: "密码长度不能少于8位",
      trigger: "blur",
    },
    {
      max: 36,
      message: "密码长度不能超过36位",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
});

const handleError = (err: any) => {
  console.log("uploadError:" + err);
};

const handleAvatarSuccess = (res: any) => {
  avatarShowUrl.value = baseUrl + "/public/uploads/" + res.data.filename;
  registerForm.avatar = res.data.filename;
  // console.log(registerForm);
};

const beforeAvatarUpload = (file: any) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (isJPG || isPNG) {
    if (!isLt2M) {
      ElMessage.error("上传头像图片大小不能超过 2MB!");
    }
  } else {
    ElMessage.error("上传头像图片只能是 JPG|PNG 格式!");
  }
};

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      // console.log("登录", toRaw(loginForm));
      const response: any = await login(toRaw(loginForm));
      // console.log(response);
      if (response.code !== 0) {
        loading.value = false;
        ElMessage.error(response.message);
        loading.value = false;
        return;
      } else {
        loading.value = false;
        ElMessage.success("登录成功！");
        store.commit("setUserInfo", response.data.user);
        store.commit("setLoginStatus", true);
        store.commit("setToken", response.data.accessToken);
        router.push("/");
        return;
      }
    }
  });
};

const onRegister = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      if (registerForm.avatar === "") {
        ElMessage.error("请上传头像");
        return;
      }
      loading.value = true;
      // console.log("注册", toRaw(registerForm));
      const data: any = await register(toRaw(registerForm));
      // console.log(data);
      if (data.code !== 0) {
        ElMessage.error(data.message);
        loading.value = false;
        return;
      } else {
        loading.value = false;
        ElMessage.success("注册成功！");
        useLoginForm.value = true;
        return;
      }
    }
  });
};

const toggleForm = () => {
  useLoginForm.value = !useLoginForm.value;
};

function onkeypress({ code }: KeyboardEvent) {
  if (["Enter", "NumpadEnter"].includes(code)) {
    useLoginForm.value
      ? onLogin(loginFormRef.value)
      : onRegister(registerFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<style scoped>
@import url("@/style/login.css");
</style>